﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Web;
using DAL = KC.DataAccess.Global.SQL;

namespace KC.Presentation.PassiveIncome
{
	public partial class Main : Form
	{
		private string ConnStr = System.Configuration.ConfigurationManager.ConnectionStrings["SQL"].ConnectionString;
		private const string RssFooter = @"</channel></rss>";
		
		public Main() { InitializeComponent(); }


		private void GenerateSpammyRss()
		{
			

		}

		private void Main_Load(object sender, EventArgs e)
		{
			tTwitterNews.Start();
		}

		private async void tTwitterNews_Tick(object sender, EventArgs e)
		{
			if (cbSentences.Checked) await PublishGibberishes();
			if (cbArticles.Checked) await RepublishArticles();
			else if (cbHubPages.Checked) await RepublishHubpages();
			else if (cbBlogPosts.Checked) await RepublishBlogPosts();
		}
		private async Task<string> PublishGibberishes()
		{
			return "";
		}
		private async Task<string> RepublishArticles()
		{
			return "";
		}
		private async Task<string> RepublishHubpages()
		{
			return "";
		}
		private async Task<string> RepublishBlogPosts()
		{
			DataRow dr = (await DAL.ExecuteDataTable(ConnStr, "select top 1 * from mv8..posts order by newid()")).Rows[0];
			string header = await GetRssHeader(ConnStr, "http://www.kconnolly.net");
			string body = dr["Body"].ToString().Replace("<"," ").Replace(">"," ").Replace("\r","").Replace("\n"," ");
			while (body.Contains("  ")) body=body.Replace("  "," ");
			if (body.Length > 500) body = body.Substring(0,495)+"[...]";
			string item = "<item><title>" + HttpUtility.HtmlEncode(dr["Title"].ToString()) + "</title><description>" + HttpUtility.HtmlEncode(body) + "</description><link>http://www.kconnolly.net/Post.aspx?Title=" + dr["FriendlyName"].ToString() + "</link><pubDate>" + string.Format("{0:R}", (DateTime)dr["Published"]) + "</pubDate></item>";


			return "";
		}
		private async Task<string> GetRssHeader(string ConnStr, string url)
		{
			string sentence = (string)(await DAL.ExecuteScalar(ConnStr, "select top 1 * from sentences where len(sentence) between 100 and 115 order by newid()"));
			for (int i = 0; i < sentence.Length && sentence.Length < 120; i++)
				if (sentence[i] == ' ' && new Random().Next(0, 10) > 5) 
					sentence.Insert(i, "#");

			return "<rss version=\"2.0\"><channel><title>Kevin Connolly's blog</title><link>" + url + "</link><description>" + System.Web.HttpUtility.HtmlEncode(sentence) + "</description>";
		}


		private string PickRandomRssFeed()
		{
			string[] feeds = txtFeeds.Text.Trim().Replace("\r", "").Split('\n');
			return feeds[new Random().Next(0, feeds.Length - 1)];
		}

	}

}
